package com.caochenlei.controller;

import com.caochenlei.pojo.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;

@RestController
public class ProductController {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping("/consumer/product/findAll")
    public List<Product> findAll() {
        //获取注册中心服务列表
        List<ServiceInstance> instances = discoveryClient.getInstances("SERVICE-PROVIDER");
        if (CollectionUtils.isEmpty(instances)) {
            return null;
        }

        //循环遍历打印服务实体
        for (ServiceInstance instance : instances) {
            System.out.println(instance.getUri());
            System.out.println(instance.getHost());
            System.out.println(instance.getPort());
            System.out.println("====================");
        }

        //我们拿出第一个服务实体
        ServiceInstance si = instances.get(0);
        String findAllUrl = si.getUri() + "/provider/product/findAll";
        Product[] products = restTemplate.getForObject(findAllUrl, Product[].class);
        return Arrays.asList(products);
    }
}
